import { Table, Input , Col, Row, Button ,Tree,DatePicker ,message, Modal,Select,Space,Menu } from 'antd';

import React, { useState, useEffect} from 'react';

import { DownOutlined,PaperClipOutlined,SearchOutlined} from '@ant-design/icons';
import { reportByArea ,queryArealistAndSet} from '@/services/energyAnalysis';


import { numberConversion } from '@/utils/utils';
import styles from './style.less'
import moment from 'moment'
const { Option } = Select;

const Report: React.FC = () => {


  const cs = [
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
      width: 100,
      // fixed: 'left',
      
    }
  ];

 const [columns, setColumns] = useState(cs);
const [selectData, setSelectData] = useState();

const [type, setType] = useState('date');
const [cdate, setCdate] = useState(moment());
const [xwidth, setXwidth] = useState(1000);
const [loading, setLoading] = useState<boolean>(true);


  useEffect(() => {
    setAnalysisData(cdate,type);
  }, [type,cdate])
  

  useEffect(() => {
    setDevice();
  }, [])
  
 
    const setDevice = async () => {
      let resultData = await queryArealistAndSet({  parentId: 0 });
      console.log(resultData)
      let areaList =resultData.list;
      let multiplier=resultData.multiplier||4000;
      let conversion=resultData.conversion||0.1229;
      if(columns.length==1){
        let newColumns=[...columns];
        for(let i=0;i<areaList.length;i++){
          let sub=areaList[i]?.areaId;
          newColumns.push( {
            title: areaList[i]?.areaName,
            children: [
              {
                title: '总电能',
                dataIndex: 'valuea'+sub,
                key: 'valuea'+sub,
                render: (text, _,record) => 
                 <>{numberConversion(text*multiplier)}</>
              }, 
              {
                title: '本期折标',
                dataIndex: 'valuea'+sub,
                render: (text, _,record) => 
                 <>{numberConversion(text*multiplier*conversion)}</>
              }, 
              {
                title: '有功',
                dataIndex: 'valueb'+sub,
                key: 'valueb'+sub,
               
              
              },
              {
                title: '无功',
                dataIndex: 'valuec'+sub,
                key: 'valuec'+sub,
             
              
              }
            ],
          },)
        }
        setColumns(newColumns);
        setXwidth(areaList.length*400)
      }
  }
  
  

  const setAnalysisData = async (pdate,ptype) => {
   
    let date=formatTime(pdate);

    const analysis = await reportByArea({type:ptype,date:pdate==null?null:date});
    setLoading(false);
    setSelectData(analysis);

   }


   function weekOfMonth (m: any) {
    return Math.ceil(m.date() / 7);
}

   function getYearWeek (weekData: any) {
    const startDate = moment(weekData).startOf('week');
    let weekMonth = weekOfMonth(startDate);
    let date = startDate.format('YYYY年MM月');
    return `${date}第${weekMonth}周`;
}

  function PickerWithType({ type, onChange }) {
    if (type === 'date') return <DatePicker  value={cdate}  popupStyle={{ background: 'rgb(20, 49, 115)'}}   bordered={false}  onChange={onChange} />;
    return <DatePicker  value={cdate} popupStyle={{ background: 'rgb(20, 49, 115)'}}     bordered={false}  picker={type} onChange={onChange} />;
  }


    const ToExport = async () => {
      const hide = message.loading('导出中');
      try {
       
        window.location.href="/api/energy/reportByArea/export?type="+type+"&date=" +formatTime(cdate);
        return true;
      } catch (error) {
        hide();
        message.error('导出失败请重试！');
        return false;
      }
    };
    

    const  formatTime = (pdate) => {
      let date=moment(pdate).format("YYYY-MM-DD");
      if(type=="week"){
        date= moment(pdate).startOf('week').format('YYYY-MM-DD');
      }else if(type=="month"){
        date= moment(pdate).startOf('month').format('YYYY-MM-DD');
      }else if(type=="quarter"){
        date= moment(pdate).startOf('quarter').format('YYYY-MM-DD');
      }else if(type=="year"){
        date= moment(pdate).startOf('year').format('YYYY-MM-DD');
      }
     
      return  date;
    }
    

   
    function SwitchablePicker() {
      return (
        <Space>
          <div  className={styles.inputBg} >
            <Select value={type}  bordered={false}    dropdownStyle={{ background: 'rgb(20, 49, 115)'}}  onChange={setType}>
              <Option value="date">日</Option>
              <Option value="week">周</Option>
              <Option value="month">月</Option>
              <Option value="quarter">季度</Option>
              <Option value="year">年</Option>
            </Select>
          </div>
          <div  className={styles.inputBg} >
            <PickerWithType type={type} onChange={value =>{ setCdate(value)}} />
          </div>(kw·h)
        </Space>
      );
    }


    return (
      <div  className={styles.main}>
        <Row className={styles.tabletop}>
          <SwitchablePicker />
          <Button className={styles.exporttBtn}  onClick={()=>ToExport()}
            type="primary" >
            <PaperClipOutlined />
            导出
          </Button> 
        </Row>
        <Table 
        loading={loading}
          columns={columns}   scroll={{ x: xwidth }} 
          rowKey="time"  dataSource={selectData}   pagination={{ position: ['none','none'] , pageSize: 31}} > 
        </Table>
    </div>
    );
};

export default Report;